"""
relog.py - 日志记录工具（改进版）
功能：
1. 日志文件存储在./log目录下
2. 文件名格式为：年.月.日_原文件名（如：log/25.8.19_sra.log）
3. 保留原始接口不变
"""

import time, os
from datetime import datetime

# 全局内存缓冲区
temp = []

def _get_dated_filename(original_name):
    """生成带日期的文件名"""
    # 创建日志目录（如果不存在）
    log_dir = "log"
    if not os.path.exists(log_dir):
        os.makedirs(log_dir, exist_ok=True)
    
    # 生成日期前缀（年.月.日）
    date_prefix = datetime.now().strftime("%y.%m.%d")
    return os.path.join(log_dir, f"{date_prefix}_{original_name}")

def init_log(filename=None):
    if filename is None:
        return "text != None"
    
    dated_filename = _get_dated_filename(filename)
    with open(dated_filename, 'w', encoding='utf-8') as w:
        time_now = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        w.write(f'[{time_now}]:初始化完成...\n')
    return "success"

def mem(text=None, *e):
    if text is None:
        return "text != None"
    
    try:
        time_now = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        temp.append(f'[{time_now}]:{text}\n')
        return "success"
    except Exception as e:
        return f"错误：添加日志失败 - {str(e)}"

def write(filename=None, text=None, *e):
    if text is None:
        if filename is None or not temp:
            return "text != None"
        
        try:
            dated_filename = _get_dated_filename(filename)
            
            # 如果文件不存在则初始化
            if not os.path.isfile(dated_filename):
                init_log(filename)  # 传入原始文件名
            
            # 写入缓冲区内容
            with open(dated_filename, 'a', encoding='utf-8') as w:
                for entry in temp:
                    w.write(entry)
            temp.clear()
            return "success"
        except PermissionError:
            return "错误：文件写入权限不足"
        except FileNotFoundError:
            return "错误：文件路径不存在"
        except Exception as e:
            return f"错误：文件写入失败 - {str(e)}"
    
    else:
        try:
            dated_filename = _get_dated_filename(filename)
            with open(dated_filename, 'a', encoding='utf-8') as w:
                time_now = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
                w.write(f'[{time_now}]:{text}\n')
            return "success"
        except PermissionError:
            return "错误：文件写入权限不足"
        except FileNotFoundError:
            return "错误：文件路径不存在"
        except Exception as e:
            return f"错误：文件写入失败 - {str(e)}"

def clean_mem(*e):
    try:
        temp.clear()
        return "success"
    except Exception as e:
        return f"错误：清空缓冲区失败 - {str(e)}"